/*!
 * jQuery zTree Plugin v1.0
 *
 * Copyright (c) 2017 PASIS
 * Create By DuanWenJie
 
 */
(function($) {
    $.fn.extend({
        /**
         * 框架内容页左侧树形结构
         * 主要用户栏目选择和组织机构选择
         *
         * options {
		 * 	id：tree元素ID
		 * 	nodes：简单数据 例如：
		 * 		var nodes = [
		 * 		{id:1, pid:0, name: "父节点1", icon: "../images/abc.gif", canclick: false},
		 * 		{id:11, pid:1, name: "子节点1"},
		 * 		{id:12, pid:1, name: "子节点2"}
		 * 		];
		 * 	idKey：id的数据字段名称，一般默认id
		 *	name：节点显示数据
		 *	pIdKey：父节点字段名称
		 *	rootPId：根节点修正值，默认-1，是因为数据库pid一般最小为0，为了再添加个根节点而修正的
		 * 	defaultValue：默认选择的值
		 * 	showIcon：是否显示图标
		 * 	redirect_url：点击狗跳转url
         * @param  redirect_param      [跳转参数]
         * array[
         * 		{'key' : '传递的参数名', 'name' : '节点上的参数名'},
         *         		……
         * ]
         * @param  parent_can_redirect [父节点是否可跳转 默认值：true]
         * @param  check 复选规则，参考zTree
         *
         * @author 段文杰
         * @date   2017-07-12
         */
        "LeftTree": function(options, onDblClick) {
            // 基础数据
            var defaults = {
                'id': $(this).attr('id'),
                'nodes': {},
                'idKey': 'id',
                'name': 'name',
                'pIdKey': 'pid',
                'rootPId': '-1',
                'root_text': '',
                'root_image': '',
                'root_image_close': '',
                'root_image_open': '',
                'defaultValue': '',
                'showIcon': true,
                'redirect_url': '',
                'redirect_param': {},
                'parent_can_redirect': true,
                'default_title': true,
                'check': {},
                'canClick': true,
                'callback': {
                    beforeAsync: null,
                    beforeCheck: null,
                    beforeClick: null,
                    beforeCollapse: null,
                    beforeDblClick: null,
                    beforeDrag: null,
                    beforeDragOpen: null,
                    beforeDrop: null,
                    beforeEditName: null,
                    beforeExpand: null,
                    beforeMouseDown: null,
                    beforeMouseUp: null,
                    beforeRemove: null,
                    beforeRename: null,
                    beforeRightClick: null,
                    onAsyncError: null,
                    onAsyncSuccess: null,
                    onCheck: null,
                    onClick: null,
                    onCollapse: null,
                    onDblClick: null,
                    onDrag: null,
                    onDragMove: null,
                    onDrop: null,
                    onExpand: null,
                    onMouseDown: null,
                    onMouseUp: null,
                    onNodeCreated: null,
                    onRemove: null,
                    onRename: null,
                    onRightClick: null
                }
            };
            $.extend(defaults, options || {});
            if (defaults.callback.onClick == null && defaults.canClick) {
                defaults.callback.onClick = treeOnClick;
            }
            // 根节点名称设置
            if (defaults.root_text != '') {
                var arr = {};
                arr[defaults.idKey] = 0;
                arr[defaults.pIdKey] = defaults.rootPId;
                arr[defaults.name] = defaults.root_text;
                if (defaults.root_image) {
                    arr.icon = defaults.root_image;
                    arr.iconClose = defaults.root_image_close;
                    arr.iconOpen = defaults.root_image_open;
                }
                defaults.nodes.push(arr);
            }

            var title = defaults.default_title ? '' : 'title';
            var setting = {
                view: {
                    dblClickExpand: true,
                    selectedMulti: false,
                    showIcon: defaults.showIcon
                },
                data: {
                    key: {
                        name: defaults.name,
                        title: title
                    },
                    simpleData: {
                        idKey: defaults.idKey,
                        pIdKey: defaults.pIdKey,
                        enable: true,
                        rootPId: defaults.rootPId
                    }
                },
                check: {},
                callback: defaults.callback
            };
            if (defaults.check != '') {
                setting.check = defaults.check;
            }
            // 实例化zTree
            var treeObj = $.fn.zTree.init($("#" + defaults.id), setting, defaults.nodes);
            // 默认展开所有节点
            treeObj.expandAll(true);
            // 默认选择节点判断
            if (defaults.defaultValue == -1) {
                var nodes = treeObj.getNodes();
                if (nodes.length > 0) {
                    treeObj.selectNode(nodes[0]);
                    if (defaults.canClick) {
                        treeObj.setting.callback.onClick(null, treeObj.setting.treeId, nodes[0]);
                    }
                }
            } else {
                var node = treeObj.getNodeByParam("id", defaults.defaultValue);
                if (node) {
                    treeObj.selectNode(node);
                    if (defaults.canClick) {
                        treeObj.setting.callback.onClick(null, treeObj.setting.treeId, node);
                    }
                }
            }
            return treeObj;

            // 点击节点跳转事件
            function treeOnClick(treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj(defaults.id);
                var node = zTree.getSelectedNodes();
                // 跳转参数处理
                var param = '';
                if (isArray(defaults.redirect_param)) {
                    for (var i = 0; i < defaults.redirect_param.length; i++) {
                        if (node[0][defaults.redirect_param[i].name] != undefined) {
                            param += defaults.redirect_param[i].key + '=' + node[0][defaults.redirect_param[i].name] + '&';
                        } else {
                            param += defaults.redirect_param[i].key + '=' + defaults.redirect_param[i].name + '&';
                        }
                    }
                    if (param != '') {
                        param = param.substring(0, param.length - 1);
                        param = '?' + param;
                    }
                }

                // 判断父节点是否可跳转
                if (defaults.parent_can_redirect) {
                    if (node[0][defaults.idKey] > -1) {
                        $("#page_frame").attr("src", defaults.redirect_url + param);
                    }
                } else {
                    if (!node[0].isParent) {
                        if (node[0][defaults.idKey] > -1) {
                            $("#page_frame").attr("src", defaults.redirect_url + param);
                        }
                    }
                }
            }
        },

        /**
         * 树形下拉菜单
         *
         * options {
		 * 	id：tree元素ID
		 * 	nodes：简单数据 例如：
		 * 		var nodes = [
		 * 		{id:1, pid:0, name: "父节点1", icon: "../images/abc.gif", canclick: false},
		 * 		{id:11, pid:1, name: "子节点1"},
		 * 		{id:12, pid:1, name: "子节点2"}
		 * 		];
		 * 	idKey：id的数据字段名称，一般默认id
		 *	name：节点显示数据
		 *	pIdKey：父节点字段名称
		 *	rootPId：根节点修正值，默认-1，是因为数据库pid一般最小为0，为了再添加个根节点而修正的
		 * 	defaultValue：默认选择的值
		 * 	showIcon：是否显示图标
		 * 	selectedMulti：是否可以多选
		 * 	height：下拉菜单高度
		 *  check： 复选规则，参考zTree
		 * 	afterClick: 点击事件后执行事件
		 * }
         *
         * @author 段文杰
         * @date   2017-07-12
         */
        "SelectTree": function(options) {
            // 基础数据
            var defaults = {
                'id': $(this).attr('id'),
                'nodes': {},
                'idKey': 'id',
                'name': 'name',
                'pIdKey': 'pid',
                'rootPId': '-1',
                'rootText': '',
                'root_image': '',
                'defaultValue': '',
                'showIcon': false,
                'selectedMulti': false,
                'height': 150,
                'check': null,
                'afterClick': null,
                'onClick': null,
                'onCheck': null,
                '_callback':null
            };
            $.extend(defaults, options || {});

            // 根节点名称设置
            if (defaults.rootText != '') {
                var arr = {};
                arr[defaults.idKey] = 0;
                arr[defaults.pIdKey] = defaults.rootPId;
                arr[defaults.name] = defaults.rootText;
                if (defaults.root_image) {
                    arr.icon = defaults.root_image;
                }
                defaults.nodes.push(arr);
            }

            var callback;
            var hasCheck = false;
            if (defaults.check == null) {
                callback = {
                    onClick: defaults.onClick == null ? onClick : defaults.onClick
                };
                defaults.check = {};
            } else {
                hasCheck = true;
                callback = {
                    onCheck: defaults.onCheck == null ? onCheck : defaults.onCheck,
                    beforeClick: beforeCheckClick
                };
            }

            var setting = {
                view: {
                    dblClickExpand: false,
                    selectedMulti: defaults.selectedMulti,
                    showIcon: defaults.showIcon
                },
                data: {
                    key: {
                        name: defaults.name
                    },
                    simpleData: {
                        idKey: defaults.idKey,
                        pIdKey: defaults.pIdKey,
                        enable: true,
                        rootPId: defaults.rootPId
                    }
                },
                check: defaults.check,
                callback: callback
            };
            // 构建树形结构节点
            var treeHtml = $('<div></div>').attr('id', 'tree_box_' + defaults.id).css({
                'margin-top': '1px',
                'border': '1px solid #D2D2D2',
                'border-radius': '2px',
                'box-shadow': '0 2px 4px rgba(0,0,0,.12)',
                'display': 'none',
                'position': 'absolute',
                'background': '#fff',
                'height': defaults.height + 'px',
                'overflow-y': 'scroll',
                'overflow-x': 'auto',
                'width': (this.outerWidth() - 2) + 'px'
            });
            treeHtml.append($('<ul></ul>').attr('id', 'tree_ul_' + defaults.id).addClass('ztree'));
            $('#tree_box_' + defaults.id).remove();
            $('body').append(treeHtml);

            // 构建隐藏域
            this.after($('<input type="hidden" name="' + this.attr('name') + '" id="' + defaults.id + '" value="' + defaults.defaultValue + '" />'));
            this.attr('name', this.attr('name') + '_old');
            this.attr('id', defaults.id + '_old');
            // 构建下箭头图标
            this.after('<i class="tree_select"></i>');

            // 点击事件
            function onClick(e, treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj(treeId);
                var nodes = zTree.getSelectedNodes();
                var v = "";
                var node_id = "";
                nodes.sort(function compare(a, b) {
                    return a[defaults.idKey] - b[defaults.idKey];
                });
                for (var i = 0, l = nodes.length; i < l; i++) {
                    v += nodes[i][defaults.name] + ",";
                    node_id += nodes[i][defaults.idKey] + ",";
                }
                if (v.length > 0) v = v.substring(0, v.length - 1);
                if (node_id.length > 0) node_id = node_id.substring(0, node_id.length - 1);
                console.log(v);
                $('#' + defaults.id + '_old').val(v);
                $('#' + defaults.id).val(node_id);
                hideMenu();
                if (defaults.afterClick != null) {
                    defaults.afterClick(e, treeId, treeNode);
                }
            }
            // 选择事件
            function onCheck(e, treeId, treeNode) {
                initCheck();
                if (defaults.afterClick != null) {
                    defaults.afterClick(e, treeId, treeNode);
                }
            }

            function initCheck() {
                var zTree = $.fn.zTree.getZTreeObj('tree_ul_' + defaults.id);
                var nodes = zTree.getCheckedNodes(true);
                var v = "";
                var node_id = "";
                for (var i = 0, l = nodes.length; i < l; i++) {
                    v += nodes[i][defaults.name] + ",";
                    node_id += nodes[i][defaults.idKey] + ",";
                }
                if (v.length > 0) v = v.substring(0, v.length - 1);
                if (node_id.length > 0) node_id = node_id.substring(0, node_id.length - 1);
                var dd=v.replace(/<\/?.+?>/g,"");
                var newsV=dd.replace(/ /g,"");//dds为得到后的内容
                $('#' + defaults.id + '_old').val(newsV);
                $('#' + defaults.id).val(node_id);
            }
            // 选择点击前事件
            function beforeCheckClick(treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj(treeId);
                zTree.checkNode(treeNode, !treeNode.checked, null, true);
                return false;
            }
            // 显示
            function showMenu(obj) {
                $(obj).next('.tree_select').addClass('show');
                var offset = obj.offset();
                $("#tree_box_" + defaults.id).css({
                    left: offset.left + "px",
                    top: offset.top + obj.outerHeight() + "px"
                }).slideDown("fast");
                $("body").bind("mousedown", onBodyDown);
            }
            // 隐藏
            function hideMenu() {
                if ($('.tree_select').hasClass('show')) {
                    $('.tree_select').removeClass('show');
                }
                $("#tree_box_" + defaults.id).fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);
            }

            function onBodyDown(event) {
                if (!(event.target.id == "menuBtn" || event.target.id == "tree_box_" + defaults.id || $(event.target).parents("#tree_box_" + defaults.id).length > 0)) {
                    hideMenu();
                }
            }
            // 初始化zTree
            var treeObj = $.fn.zTree.init($('#tree_ul_' + defaults.id), setting, defaults.nodes);
            treeObj.expandAll(true);
            var node = treeObj.getNodeByParam(defaults.idKey, defaults.defaultValue);
            if (node) {
                treeObj.selectNode(node);
                $('#' + defaults.id + '_old').val(node[defaults.name]);
                $('#' + defaults.id).val(node[defaults.idKey]);
            }

            if (hasCheck) {
                initCheck();
            }

            $(this).focus(function() {
                $(this).click();
            });
            $(this).bind("click", function() {
                $('tree_ul_' + defaults.id).width($(this).width() - 20);
                showMenu($(this));
            });
            //2018年8月27日 赵泽东新增下拉框模糊查询
            if(defaults._callback != null) defaults._callback();
        }
    });
})(jQuery);